package chat.model;


import com.orm.SugarRecord;
import com.whu.administrator.ws.MyApplication;

import java.util.ArrayList;
import java.util.List;

import model.Message;

/**
 * Created by 凯 on 2015/10/29.
 */
public class ChatModel {

    Long smallId = Long.MAX_VALUE;
    Long bigId = Long.MAX_VALUE;

    public static final String OLDNUM = "30";

    String FriendID;
    String OwnID = MyApplication.getOwnUser().getUser_ID();

    List<Message> messages = new ArrayList<Message>();

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }

    public void setFriendID(String friendID) {
        FriendID = friendID;
    }

    public ChatModel() {
    }


    public void init()
    {
        List<Message> oldMsgs = SugarRecord.findWithQuery(Message.class, "Select * from message where (userfromid = ? or userfromid = ?) and id < ? order by id desc  limit 0,10", FriendID + "", OwnID + "", smallId + "");
        if (oldMsgs != null && !oldMsgs.isEmpty())
        {
            smallId = oldMsgs.get(oldMsgs.size()-1).getId();
            bigId = oldMsgs.get(0).getId();
        }
        else
        {
            smallId = bigId = 0l;
        }
        for (Message message:oldMsgs)
        {
            messages.add(0,message);
        }
    }

    public void getNew()
    {
        List<Message> newMsgs = SugarRecord.findWithQuery(Message.class,"Select * from message where (userfromid = ? or userfromid = ?) and id > ?",FriendID+"",OwnID+"",bigId+"");
        if (newMsgs != null && !newMsgs.isEmpty())
        {
            bigId = newMsgs.get(newMsgs.size()-1).getId();
        }

        messages.addAll(newMsgs);
    }


    public int getOld()
    {
        List<Message> oldMsgs = SugarRecord.findWithQuery(Message.class, "Select * from message where (userfromid = ? or userfromid = ?) and id < ?  limit 0,?", FriendID + "", OwnID + "", smallId + "",OLDNUM);
        if (oldMsgs != null && !oldMsgs.isEmpty())
        {
            smallId = oldMsgs.get(oldMsgs.size()-1).getId();
        }
        messages.addAll(0,oldMsgs);
        return oldMsgs.size();
    }





}
